package com.chief.hadoop.mr.join.reduce;

import com.chief.hadoop.mr.join.OrderBean;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class OrderReduce extends Reducer<Text, OrderBean, OrderBean, NullWritable> {

    @Override
    protected void reduce(Text key, Iterable<OrderBean> values, Context context) throws IOException, InterruptedException {
        List<OrderBean> list = new ArrayList<>();
        OrderBean orderBean;
        String goodsName = null;
        for (OrderBean value : values) {
            orderBean = new OrderBean();
            orderBean.setGoodsId(value.getGoodsId());
            if (StringUtils.isNotBlank(value.getGoodsName())) {
                //goods.txt
                goodsName = value.getGoodsName();
            } else {
                orderBean.setOrderId(value.getOrderId());
                orderBean.setCnt(value.getCnt());
                list.add(orderBean);
            }
        }
        for (OrderBean bean : list) {
            bean.setGoodsName(goodsName);
            context.write(bean, NullWritable.get());
        }
    }

}
